from rest_framework import status, serializers
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from apps.meiduo_admin.utils import PageNum
from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.serializers.image import SkuImageModelSerializer, ImageSKUModelSerializer
from fdfs_client.client import Fdfs_client

class SkusModelViewSet(ModelViewSet):
    """商品图片展示"""
    pagination_class = PageNum
    serializer_class = SkuImageModelSerializer
    queryset = SKUImage.objects.all()



    def create(self, request, *args, **kwargs):
        """重写create方法保存图片"""
        # 接收数据
        image = request.data.get('image')
        sku_id = request.data.get('sku')
        image_data = image.read()
        # 验证参数
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        client = Fdfs_client('utlis/fastdfs/client.conf')
        # 上传图片
        result = client.upload_by_buffer(image_data)
        #  根据上传的结果 获取file_id
        if result['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_400_BAD_REQUEST)
        file_id = result.get('Remote file_id')
        #  保存SKUImage
        new_image = SKUImage.objects.create(
            sku_id=sku_id,
            image=file_id
        )
        # 返回响应
        return Response({
            'id': new_image.id,
            'sku': sku_id,
            'image': new_image.image.url
        }, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        """重写方法实现更新图片"""
        # 接收数据
        image = request.data.get('image')
        sku_id = request.data.get('sku')
        image_data = image.read()
        # 验证是否上传成功
        client = Fdfs_client('utlis/fastdfs/client.conf')
        result = client.upload_by_buffer(image_data)
        if result['Status'] != 'Upload successed.':
            return serializers.ValidationError('上传失败请稍后在试')
        file_id = result.get('Remote file_id')
        sku_image = SKUImage.objects.get(id=kwargs['pk'])
        sku_image.image = file_id
        sku_image.save()
        return Response(
            {
                'id': sku_image.id,
                'sku': sku_id,
                'image': sku_image.image.url
            },
            status=201
        )
class SKUIdView(APIView):
    """获取所有skuid"""
    def get(self,request):
        date = SKU.objects.all()
        slz = ImageSKUModelSerializer(date,many=True)
        return Response(slz.data)